package com.example.demo.controller;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.TemplateExportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import com.example.demo.model.*;
import com.example.demo.servcie.DataImportService;
import com.example.demo.servcie.impl.CleaningServiceImpl;
import com.example.demo.utils.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.*;

@Slf4j
@RestController
@RequestMapping("/poi")
public class EasyPoiController {

    private DataImportService importService;

    public EasyPoiController(CleaningServiceImpl cleaningService) {
        this.importService = cleaningService;
    }

    @GetMapping(value = "importPage")
    public ModelAndView importPage(ModelAndView mv) {
        mv.setViewName("import");
        return mv;
    }

    @GetMapping(value = "exportPage")
    public ModelAndView exportPage(ModelAndView mv) {
        mv.setViewName("export");
        return mv;
    }

    /**
     * 导入excel数据
     *
     * @param file
     * @return
     * @throws IOException
     */
    @PostMapping(value = "/import", produces = "application/json;charset=UTF-8")
    public ResponseEntity<Result<String>> importExcel(MultipartFile file, Integer userId,
                                                      String batchNo, HttpServletResponse response) throws IOException {
        List<User> list = ExcelUtil.getInstance().importExcel(file, 0, 1, User.class);
        return new ResponseEntity<>(importService.importData(userId, batchNo, file, response), HttpStatus.OK);
    }

    /**
     * 导入excel数据
     *
     * @return
     * @throws IOException
     */
    @PostMapping(value = "/import1", produces = "application/json;charset=UTF-8")
    public ResponseEntity<String> importExcel1(@RequestParam("file") MultipartFile file, @RequestBody(required = false) ImportModel req) throws IOException {
        List<User> list = ExcelUtil.getInstance().importExcel(file, 0, 1, User.class);
        return ResponseEntity.ok("导入成功");
    }


    /**
     * 导入excel数据
     *
     * @param file
     * @return
     * @throws IOException
     */
    @PostMapping(value = "/import2", consumes = MediaType.MULTIPART_FORM_DATA_VALUE, produces = "application/json;charset=UTF-8")
    public ResponseEntity<String> importExcel2(@RequestParam("file") MultipartFile file) throws IOException {
        List<User> list = ExcelUtil.getInstance().importExcel(file, 0, 1, User.class);
        return ResponseEntity.ok("导入成功");
    }


    /**
     * 导出数据
     * // http://localhost:8080/poi/exportExcel
     *
     * @param response
     * @throws IOException
     */
    @GetMapping("/exportExcel")
    public ResponseEntity<String> exportExcel(@RequestParam(value = "orgCode") String orgCode, HttpServletResponse response) throws IOException {
        List<User> list = new ArrayList<User>() {{
            add(User.builder().userName("userName1").age(16).name("张三").sex("0").address("北京").build());
            add(User.builder().userName("userName2").age(17).name("李四").sex("1").address("上海").build());
            add(User.builder().userName("userName3").age(18).name("王五").sex("男").address("广州").build());
        }};
        ExcelUtil.getInstance().exportExcel(list, User.class, "用户信息统计导出", response);
        return new ResponseEntity<>("用户信息统计导出", HttpStatus.OK);
    }

    /**
     * 导出数据
     * // http://localhost:8080/poi/exportExcel1
     *
     * @param response
     * @throws IOException
     */
    @PostMapping(value = "/exportExcel1")
    public void exportExcel1(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String name = request.getParameter("name");
        List<User> list = new ArrayList<User>() {{
            add(User.builder().userName("userName1").age(16).name("张三").sex("0").address("北京").build());
            add(User.builder().userName("userName2").age(17).name("李四").sex("1").address("上海").build());
            add(User.builder().userName("userName3").age(18).name("王五").sex("男").address("广州").build());
        }};
        ExcelUtil.getInstance().exportExcel(list, "用户信息统计表Title", "用户表Sheet", User.class, "用户信息统计File", response);
    }


    /**
     * excel带图片的导出
     * // http://localhost:8080/poi/imgexport
     *
     * @param response
     * @throws IOException
     */
    @GetMapping("/imgexport")
    public void imgExport(HttpServletResponse response) throws IOException {
        List<Company> list = new ArrayList<>();
        //图片的路径自定义，但必须要正确
        list.add(new Company("百度", "E:/img/1.jpg", "百度一下你就知道"));
        list.add(new Company("腾讯", "E:/img/3.jpg", "腾讯qq,交流的世界"));
        list.add(new Company("阿里巴巴", "E:/img/2.jpg", "阿里巴巴，马云的骄傲"));
        ExcelUtil.getInstance().exportExcel(list, "图片excelTile", "图片excelSheet", Company.class, "图片excelFile", response);
    }

    /**
     * excel带图片的导入  只支持在linux服务器上 (可以自行查看源码)
     * // http://localhost:8080/poi/imgexport
     *
     * @param file
     * @return
     * @throws IOException
     */
    @PostMapping("/imgimport")
    public ResponseEntity imgImport(@RequestParam("file") MultipartFile file) throws IOException {
        List<Company> list = ExcelUtil.getInstance().importExcel(file, Company.class);
        return ResponseEntity.ok("导入成功:" + list);
    }


    /**
     * 使用模板excel导出  (专门处理一些复杂情况下的数据导出)
     * http://localhost:8080/poi/excelTemplate
     *
     * @param response
     * @throws Exception
     */
    @GetMapping("/excelTemplate")
    public void makeExcelTemplate(HttpServletResponse response) throws Exception {
        List<User> list = new ArrayList<User>() {{
            add(User.builder().userName("userName1").age(16).name("张三").sex("0").address("北京").mobile("13188888888").build());
            add(User.builder().userName("userName2").age(17).name("李四").sex("1").address("上海").mobile("13188888889").build());
            add(User.builder().userName("userName3").age(18).name("王五").sex("男").address("广州").mobile("13188888880").build());
        }};
        Map<String, Object> dataMap = new HashMap<>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        dataMap.put("date", sdf.format(new Date()));
        dataMap.put("user", "admin");
        dataMap.put("dataList", list);
        String filePath = FileUtil.getInstance().getClassPath() + "\\files\\导出测试模板.xlsx";
        ExcelUtil.getInstance().exportExcel(filePath, "D:/temp/导出测试模板" + System.currentTimeMillis() + ".xlsx", dataMap);
    }

    /**
     * 使用模板excel导出  (专门处理一些复杂情况下的数据导出)
     * http://localhost:8080/poi/excelTemplate1
     *
     * @param response
     * @throws Exception
     */
    @PostMapping("/excelTemplate1")
    public void makeExcelTemplate1(@RequestBody(required = false) ExportReq req, HttpServletResponse response) throws Exception {
        List<User> list = new ArrayList<User>() {{
            add(User.builder().userName("userName1").age(16).name("张三").sex("0").address("北京").mobile("13188888888").build());
            add(User.builder().userName("userName2").age(17).name("李四").sex("1").address("上海").mobile("13188888889").build());
            add(User.builder().userName("userName3").age(18).name("王五").sex("男").address("广州").mobile("13188888880").build());
        }};
        List<Map<String, Object>> dataMap = new ArrayList<>();
        list.forEach(d -> {
            dataMap.add(JacksonUtil.jsonToMap(JacksonUtil.beanToJson(d), Object.class));
        });
        List<Map<String, Object>> exportList = new ArrayList<>();
        Map<String, Object> tempMap = new HashMap<>();
        List<String> fields = req.getFields();
        if (CollectionUtils.isNotEmpty(req.getFields())) {
            req.getFields().forEach(o -> {
                dataMap.forEach(data -> {
                    data.forEach((k, v) -> {
                        if (o.equals(k)) {
                            tempMap.put(o, v);
                        }
                    });
                    exportList.add(tempMap);
                });
            });
        }

        Map<String, Object> map = new HashMap<>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        map.put("title", "导出测试模板" + sdf.format(new Date()));
        map.put("date", sdf.format(new Date()));
        map.put("user", "张三");
        map.put("entity", fields);
        map.put("dataList", exportList);
        String filePath = FileUtil.getInstance().getClassPath() + "\\files\\导出测试模板.xlsx";
        TemplateExportParams params = new TemplateExportParams(filePath);
        OutputStream outputStream = new FileOutputStream("D:/temp/导出测试模板" + System.currentTimeMillis() + ".xlsx");
        Workbook workbook = ExcelExportUtil.exportExcel(params, map);
        workbook.write(outputStream);
        outputStream.flush();
    }


    /**
     * 使用注解导出
     * http://localhost:8080/poi/excelTemplate2
     *
     * @throws Exception
     */
    @PostMapping(value = "/excelTemplate2", produces = "application/json;charset=UTF-8")
    public ResponseEntity<String> makeExcelTemplate2() throws Exception {
        List<User> list = new ArrayList<User>() {{
            add(User.builder().userName("userName1").age(16).name("张三").sex("0").address("北京").mobile("13188888888").build());
            add(User.builder().userName("userName2").age(17).name("李四").sex("1").address("上海").mobile("13188888889").build());
            add(User.builder().userName("userName3").age(18).name("王五").sex("男").address("广州").mobile("13188888880").build());
        }};

        String filePath = FileUtil.getInstance().getClassPath() + "\\files\\导出测试模板.xls";
        File exportFile = new File(filePath);
        ExcelUtil.getInstance().exportExcel(exportFile, list, User.class, ExcelType.HSSF);
        return new ResponseEntity<>(filePath, HttpStatus.OK);
    }


    /**
     * 使用注解导出
     * http://localhost:8080/poi/excelTemplate2
     *
     * @throws Exception
     */
    @GetMapping(value = "/excelTemplate3", produces = "application/json;charset=UTF-8")
    public ResponseEntity<String> excelTemplate3(String json) throws Exception {
        List<ExportBook> list = new ArrayList<>();
        list = JacksonUtil.jsonToList(json, ExportBook.class);
        String exportFileUrl = "D:\\temp\\uploadFile\\基础数据导出模板-图书_1686279931102.xlsx";
        File exportFile = new File(exportFileUrl);
        ExcelUtil.getInstance().exportExcel(exportFile, list, ExportBook.class, ExcelType.HSSF);
        return new ResponseEntity<>(exportFileUrl, HttpStatus.OK);
    }

    /**
     * exportPdf
     * http://localhost:8060/poi/exportPdf
     */
    @GetMapping(value = "/exportPdf", produces = "application/json;charset=UTF-8")
    public ResponseEntity<String> exportPdf() {
        String[] header = {"序号", "姓名", "数量"};
        int[] widths = {10, 12, 15};
        List<LinkedHashMap<String, Object>> dataList = new ArrayList<>();
        LinkedHashMap<String, Object> dataMap = new LinkedHashMap<>();
        dataMap.put("id", 1);
        dataMap.put("name", "张三");
        dataMap.put("count", 1.2);
        dataList.add(dataMap);
        dataMap = new LinkedHashMap<>();
        dataMap.put("id", 2);
        dataMap.put("name", "李四");
        dataMap.put("count", 1.5);
        dataList.add(dataMap);
        String path = PdfUtil.getInstance().exportPdf("测试文件", header, dataList);
        return new ResponseEntity<>(path, HttpStatus.OK);
    }


}
